package com.witdata.security.filter;

import com.witdata.security.domain.LoginUser;
import com.witdata.security.utils.JwtUtils;
import com.witdata.security.utils.TokenUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * DATETIME: 2024/2/2 23:16
 * USER: admin
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtUtils jwtUtils;
    private final TokenUtils tokenUtils;

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain) throws IOException, ServletException {
        LoginUser loginUser = tokenUtils.getLoginUser(request);
        if (!ObjectUtils.isEmpty(loginUser)) {
            request.setAttribute("userId", loginUser.getUserId());
            request.setAttribute("loginUser", loginUser);
            SecurityContext context = SecurityContextHolder.getContext();
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), loginUser.getAuthorities());
            context.setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
